package fschmidt.util.mail;

// not thread safe
public class Pop3ServerPool implements Pop3Server {
	private Pop3Server[] servers;
	private int current = 0;
	
	Pop3ServerPool(Pop3Server... servers) {
		this.servers = servers;
		setMailLimit(100);
	}
	
	public void setLeaveOnServer(boolean b) {
		for (Pop3Server server : servers) {
			server.setLeaveOnServer(b);
		}
	}
	
	public void setMailLimit(int maxMailCount) {
		for (Pop3Server server : servers) {
			server.setMailLimit(maxMailCount);
		}
	}
	
	// should be same for all
	public String getUsername() {
		return servers[current].getUsername();
	}
	
	public void useSsl() {
		for (Pop3Server server : servers) {
			server.useSsl();
		}
	}
	
	public void setDebug(boolean b) {
		for (Pop3Server server : servers) {
			server.setDebug(b);
		}
	}
	
	public MailIterator getMail() throws MailException {
		MailException ex = null;
		for (int failed = 0; failed < servers.length; failed++) {
			try {
				return mailIterator(servers[current].getMail());
			} catch (MailException e) {
				ex = e;
				nextServer();
			}
		}
		throw new MailException("all pop3 servers failed", ex);
	}
	
	private MailIterator mailIterator(final MailIterator itr) {
		return new MailIterator() {
			public boolean hasNext() throws MailException {
				return itr.hasNext();
			}
			public Mail next() throws MailException {
				return itr.next();
			}
			public void close() throws MailException {
				try {
					itr.close();
				} finally {
					nextServer(); // always switch to next server
				}
			}
		};			
	}

	private void nextServer() {
		current = (current < servers.length - 1) ? current+1 : 0;
	}
	
}
